(function(module){
	$.module.page.initView('userList');
	$.laydate.render({elem: "#userCreateTime", type: "datetime", range: ['#userCreateStartTime', '#userCreateEndTime']});
	var menuId=$.parseHrefParam('menuId');
	module[menuId]={
		tableCols: [function(){
			var cols=[//列表标题
				{ field: 'account', title: '登录账号'},
				{ field: 'phone', title: '手机号'},
				{ field: 'email', title: '电子邮箱'},
				{ field: 'nickname', title: '昵称'},
				{ field: 'name', title: '姓名'},
				{ field: 'idCardTypeName', title: '证件类型'},
				{ field: 'idCardShow', title: '证件号'},
				{ field: 'roleNames', title: '角色'},
				{ title: '状态', width:85, templet: '#userListStatusToolbar'},
				{ fixed: 'right', title:'操作', width: 200, minWidth: 200, toolbar: '#userListRowToolbar'}
			];
			var local = layui.data('userListTable'); // 获取对应的本地记录
			layui.each(cols, function(index, item) {
				if (item.field in local) {
					item.hide = local[item.field];
				}
			});
			return cols;
		}()],
		search: function(){
			module[menuId].selectRow=null;
			var search=$.formToData('userListSearchForm');
			$.table.render({
				elem: '#userListTable',
				toolbar: '#userListToolbar',
				defaultToolbar: ['filter', {title: '导出',layEvent: 'auto-export',icon: 'layui-icon-export'}, 'print'],
				url: '/system/systemUser/findPageList', // 此处为静态模拟数据，实际使用时需换成真实接口
				method: 'post',
				contentType: 'application/json',
				request: {
					pageName: 'currPage',
					limitName: 'pageSize'
				},
				parseData: function(res) { // res 即为原始返回的数据
					return {
						"code": res.code, // 解析接口状态
						"msg": res.message, // 解析提示文本
						"count": res.body.totalSize, // 解析数据长度
						"data": res.body.dataList // 解析数据列表
					};
				},
				where: search,
				cols: module[menuId].tableCols,
				page: true,
				limit: 15,
				limits: [10, 15, 30, 50, 100, 200, 500, 1000],
				height: 'full-162',
				done: function(){
					$.auth.init($("#userList"));
					module[menuId].loadEvent(this);
				}
			});
		},
		reload: function(){
			$.table.reload("userListTable", {}, true);
		},
		loadEvent: function(that){
			$.table.on('row(userListTable)', function(obj) {
				var data = obj.data; // 获取当前行数据
				obj.setRowChecked({
					type: 'radio' // radio 单选模式；checkbox 复选模式
				});
				module[menuId].selectRow=data;
				$("#userList .layui-table-tool .layui-btn").each(function(){
					var button=$(this);
					if(button.hasClass('layui-btn-disabled')){
						button.removeClass('layui-btn-disabled');
					}
				});
			});
			$.table.on('toolbar(userListTable)',function(obj){
				if(obj.event === 'add'){
					module[menuId].add();
				}else if(obj.event === 'import'){
					module[menuId].import();
				}else if(obj.event === 'edit'){
					if(!module[menuId].selectRow){
						$.error("未选定行");
						return false;
					}
					if(!module[menuId].selectRow.isAdmin){
						$.error("系统角色不能进行编辑操作");
						return false;
					}
					module[menuId].edit(module[menuId].selectRow.id);
				}else if(obj.event === 'authorize'){//授权
					if(!module[menuId].selectRow){
						$.error("未选定行");
						return false;
					}
					if(module[menuId].selectRow.isAdmin){
						$.error("系统用户不能进行授权操作");
						return false;
					}
					module[menuId].authorize(module[menuId].selectRow.id);
				}else if(obj.event === 'delete'){
					if(!module[menuId].selectRow){
						$.error("未选定行");
						return false;
					}
					if(!module[menuId].selectRow.isAdmin){
						$.error("系统角色不能进行删除操作");
						return false;
					}
					module[menuId].delete(module[menuId].selectRow.id);
				}else if(obj.event === 'auto-export'){
					module[menuId].export();
				}else if(obj.event === 'lookLogger'){
					if(!module[menuId].selectRow){
						$.error("未选定行");
						return false;
					}
					module[menuId].lookLogger(module[menuId].selectRow.id);
				}
			});
			$.table.on('tool(userListTable)', function(obj){
				var data = obj.data; // 获得当前行数据
			    if(obj.event === 'edit'){
					module[menuId].edit(data.id);
				}else if(obj.event === 'authorize'){
					module[menuId].authorize(data.id);
				}else if(obj.event === 'delete'){
					module[menuId].delete(data.id);
				}
			});
			$.form.on('switch(userStatus)', function(obj) {
				module[menuId].status(obj.value, obj.elem.checked);
			});
			that.elem.next().on('mousedown', 'input[lay-filter="LAY_TABLE_TOOL_COLS"]+', function() {
				var input = $(this).prev()[0];
				layui.data('userListTable', {
					key: input.name,
					value: input.checked
				});
			});
		},
		export: function(){
			$.module.export.handle(
				'用户导出', 
				'/imexport/systemUser/export', 
				$.formToData('userListSearchForm'), 
				'/imexport/systemUser/export/stop'
			);
		},
		import: function(){
			$.module.import.handle(
				'用户导入', 
				'systemUser', 
				'xls|xlsx', 
				'/imexport/systemUser/import', 
				'/imexport/systemUser/import/stop',
				module[menuId].reload
			);
		},
		add: function(){
			$.get('/pages/admin/system/user/userView.html', function(html){
				$.layer.open({
					title: '新建用户',
					type: 1,
					area: ['900px', '660px'],
					shade: 0.6, // 遮罩透明度
					shadeClose: true, // 点击遮罩区域，关闭弹层
					content: html,
					btn: ["确定", "取消"],
					yes: module[menuId].create,
					success: module[menuId].initForm
				});
			});
		},
		initForm: function(){
			$.dictionary.loadSelect('userViewForm', 'userIdCardType', 'idCardType');
			$.dictionary.loadSelect('userViewForm', 'userSex', 'sex');
			$.laydate.render({elem: "#userBirthday", type: "date"});
			$.form.render(null, 'userViewForm');
			$.form.on('select(userIdCardType)', module[menuId].selectIdCardType);
			$('#userViewForm [name="idCardShow"]').on("input", module[menuId].idCardShowInput);
		},
		formRules: {
			account: [
					{ required: true, message: "登录账号不能为空"},
					{ minLength: 6, maxLength: 20, message: "登录账号长须必须在6-20个字符之间"},
					{ regexp: /[0-9a-zA-Z_]+/, message: "登录账号只能输入字母、和数字或下划线"}
				],
			password: [
					{ required: true, message: "登录密码不能为空"},
					{ minLength: 6, maxLength: 20, message: "登录账号长须必须在6-20个字符之间"},
					{ regexp: /[0-9a-zA-Z_]+/, message: "登录密码只能输入字母、数字或下划线"},
					{ regexp: /^(([0-9]+)|([a-z]+)|([A-Z]+)|([_]+))$/, negate: true, message: "登录密码必须包含字母、数字或下划线中的任意两种组合"}//negate表示取反
				],
			nickname: [{ required: true, message: "昵称不能为空"}]
		},
		create: function(layerId){
			if(!$.valiForm('userViewForm', module.currModule.formRules)){
				return false;
			}
			var data=$.formToData('userViewForm');
			$.post('/system/systemUser/create', data, function(res){
				$.success("操作成功");
				module[menuId].reload();
				$.layer.close(layerId);
			}, 'json');
		},
		selectIdCardType: function(data){
			var value=data.value;
			if(value!='1'){
				$('#userViewForm [name="idCardShow"]').val("");
			}
		},
		idCardShowInput: function(){
			var value=$(this).val();
			if(value && value.length>13){
				var birthday=value.substring(6, 14);
				var year=birthday.substring(0, 4);
				var month=birthday.substring(4, 6);
				var day=birthday.substring(6, 8);
				$('#userBirthday').val(year+"-"+month+"-"+day);
				if(value.length>16){
					var sex=value.substring(16, 17);
					console.log(sex);
					$('#userViewForm [name="sex"]').val(sex%2==1?'Y':"X");
					$.form.render(null, 'userViewForm');
				}
			}
		},
		edit: function(id){
			$.get('/pages/admin/system/user/userView.html', function(html){
				$.layer.open({
					title: '编辑角色',
					type: 1,
					area: ['900px', '660px'],
					shade: 0.6, // 遮罩透明度
					shadeClose: true, // 点击遮罩区域，关闭弹层
					content: html,
					btn: ["确定", "取消"],
					yes: module[menuId].update,
					success: function(){
						$("#userViewForm [update='disabled']").attr("disabled",true);
						$("#userViewForm [update='hide']").hide();
						module[menuId].initForm();
						$.loadFormAjax('#userViewForm', 'POST', '/system/systemUser/view', $.toJson({id: id}));
					}
				});
			});
		},
		update: function(layerId){
			if(!$.valiForm('userViewForm', module.currModule.formRules)){
				return false;
			}
			var data=$.formToData('userViewForm');
			$.post('/system/systemUser/update', data, function(res){
				$.success("操作成功");
				module[menuId].reload();
				$.layer.close(layerId);
			}, 'json');
		},
		delete: function(id){
			$.layer.confirm("确定要删除此数据吗？", {btn:['确定','取消']}, function(){
				$.post('/system/systemUser/delete', {id: id}, function(data){
					$.success("操作成功");
					module[menuId].reload();
				}, 'json');
			}, function(){
				
			});
		},
		status: function(id, status){
			$.post('/system/systemUser/updateStatus',{id: id, status: status?1:0}, function(data){
				$.success("操作成功");
				module[menuId].reload();
			},'json');
		},
		authorize: function(id){
			module[menuId].selectId=id;
			$.get('/pages/admin/system/user/userAuthorize.html', function(html){
				$.layer.open({
					title: '角色授权',
					type: 1,
					area: ['700px', '300px'],
					shade: 0.6, // 遮罩透明度
					shadeClose: true, // 点击遮罩区域，关闭弹层
					content: html,
					btn: ["确定", "取消"],
					yes: module[menuId].authorized,
					success: function(){
						$.post('/system/systemUser/findAuthorizeRoleList',{userId:id},function(res){
							var dataList=res.dataList;
							var html='';
							if(dataList){
								for(var i=0, length=dataList.length; i < length; i++){
									html+='<input type="checkbox" name="roleIds" title="'+dataList[i].name+'" lay-skin="primary" value="'+dataList[i].id+'"'+(dataList[i].checked?' checked':'')+'>';
								}
							}
							$("#userRoleListView").html(html);
							$.form.render(null, 'userViewForm');
						}, 'json');
					}
				});
			});
		},
		authorized: function(layerId){
			var roleList=[];
			$("#userAuthorizeViewForm [name='roleIds']:checked").each(function(){
				var role={roleId: this.value, roleName: this.title};
				roleList.push(role)
			});
			var data={userId: module[menuId].selectId, list: roleList};
			$.post('/system/systemUser/updateAuthorize', data, function(res){
				$.success("操作成功");
				module[menuId].reload();
				$.layer.close(layerId);
			}, 'json');
		},
		lookLogger: function(id){
			$.module.logger.look('systemUser', id);
		},
		clear: function(){
			var data={account:'',createStartTime:'',createEndTime:''};
			$.loadFormData("#userListSearchForm", data);
		},
		selectDepartmentJob: function(){
			$.get('/pages/admin/system/user/departmentJobTree.html', function(html){
				$.layer.open({
					title: '选择部门/职位<span class="font12 color-red subtitle">双击选中或取消</span>',
					type: 1,
					area: ['700px', '500px'],
					shade: 0.6, // 遮罩透明度
					shadeClose: true, // 点击遮罩区域，关闭弹层
					content: html,
					btn: ["确定", "取消"],
					yes: module[menuId].confirmDepartmentJob,
					success: function(){
						var data={};
						var departmentJobIds=$("#userViewForm [name='departmentJobIds']").val();
						if(departmentJobIds){
							data.checkedJson=departmentJobIds;
						}
						$.post('/system/systemUser/findDepartmentJobTree', data, function(data){
							data.isClickStyle=true;
							var endTime, lastNode;
							$.tree.loadTree('user-department-job-tree', data, function(node){
								const currentTime = new Date().getTime();
								if(endTime && currentTime-endTime<300 && lastNode && lastNode.data.id==node.data.id){//双击
									module[menuId].moveDepartmentJobNode(node);
									return ;
								}
								endTime=currentTime;
								lastNode=node;
							});
							var checkedList=$.tree.getDataChecked(data);
							if(checkedList){
								for(var i=0, length=checkedList.length; i<length; i++){
									module[menuId].moveDepartmentJobNode({data:checkedList[i]});
								}
							}
						}, 'json');
					}
				});
			});
		},
		moveDepartmentJobNode: function(node){
			var table=$("#user-department-job-table-tbody");
			var nodeRow=table.find("[dataid='"+node.data.id+"']");
			if(nodeRow.exists()){
				nodeRow.remove();
			}else{
				var newRow=table.find(".model").clone();
				newRow.removeClass("model");
				newRow.addClass("data");
				newRow.show();
				var dataTitle=node.data.departmentName?node.data.title.replace('</i>', '</i>'+node.data.departmentName+"："):node.data.title;
				newRow.children(":eq(0)").html(dataTitle);
				newRow.attr("dataid", node.data.id).attr("dataname",dataTitle.substring(dataTitle.indexOf('</i>')+"</i>".length));
				newRow.appendTo(table);
			}
		},
		confirmDepartmentJob: function(layerId){
			var departmentJobIdList="[";
			var departmentJobNameList="";
			$("#user-department-job-table-tbody .data").each(function(){
				departmentJobIdList+="["+$(this).attr("dataid")+"],";
				departmentJobNameList+=$(this).attr("dataname")+"，";
			});
			if(departmentJobIdList.length>1){
				departmentJobIdList=departmentJobIdList.substring(0, departmentJobIdList.length-1);
				departmentJobNameList=departmentJobNameList.substring(0, departmentJobNameList.length-1);
				departmentJobIdList+=']';
			}else{
				departmentJobIdList='';
			}
			console.log(departmentJobIdList);
			console.log(departmentJobNameList);
			var form=$("#userViewForm");
			form.find("[name='departmentJobIds']").val(departmentJobIdList);
			form.find("[name='departmentJobNames']").val(departmentJobNameList);
			$.layer.close(layerId);
		},
		selectedRow: function(td){
			$("#user-department-job-table-tbody .checked").removeClass("checked");
			$(td).addClass("checked");
		}
	}
	$.module.currModule=$.module[menuId];
	module[menuId].search();
})($.module);